﻿#if STEAM_NETWORK
using Steamworks;


namespace Manox.Libs.Networking.Steam
{
    /// <summary>
    /// Steam network host.
    /// </summary>
    public class SteamNetworkHost : SteamNetworkNode, INetworkHost
    {
        /// <summary>Lobby created.</summary>
        private CallResult<LobbyCreated_t> LobbyCreated;
        /// <summary>Create response.</summary>
        public NetworkResponseDelegate<bool> CreateResponse;
        /// <summary>Lobby id.</summary>
        private CSteamID LobbyId;
        /// <summary>Game name.</summary>
        private string GameName;
        /// <summary>Password.</summary>
        public string Password;


        /// <summary>
        /// Start host.
        /// </summary>
        /// <param name="hostName"></param>
        /// <param name="playersCount"></param>
        /// <param name="publicVisible"></param>
        /// <param name="password"></param>
        /// <param name="response"></param>
        public void StartHost(string hostName, uint playersCount, bool publicVisible, string password, NetworkResponseDelegate<bool> response)
        {
            this.CreateResponse = response;
            this.GameName = hostName;
            this.Password = password;

            this.LobbyCreated = CallResult<LobbyCreated_t>.Create(this.OnLobbyCreated);            

            if (publicVisible)
                this.LobbyCreated.Set(SteamMatchmaking.CreateLobby(ELobbyType.k_ELobbyTypePublic, (int)playersCount));
            else
                this.LobbyCreated.Set(SteamMatchmaking.CreateLobby(ELobbyType.k_ELobbyTypePrivate, (int)playersCount));                       
        }

        /// <summary>
        /// On lobby created.
        /// </summary>
        /// <param name="lobbyCreated"></param>
        /// <param name="isOk"></param>
        private void OnLobbyCreated(LobbyCreated_t lobbyCreated, bool failed)
        {
            this.LobbyId = (CSteamID)lobbyCreated.m_ulSteamIDLobby;

            SteamMatchmaking.SetLobbyData(this.LobbyId, "name", this.GameName);            

            if (this.CreateResponse != null)
                this.CreateResponse(!failed && lobbyCreated.m_eResult != EResult.k_EResultOK);                                              
        }
    }
}
#endif